<template>
<div class="lectures-manage">
  <!-- <VHeader></VHeader> -->
  <div class="l-tab-box">
    <ul class="l-tab">
      <li class="l-tab-btn" :class="{selected:status==='0'}" v-click="()=>{switchState('0')}">待审批</li>
      <li class="l-tab-btn" :class="{selected:status==='1'}" v-click="()=>{switchState('1')}">未通过</li>
      <li class="l-tab-btn" :class="{selected:status==='2'}" v-click="()=>{switchState('2')}">已通过</li>
    </ul>
  </div>
  <LoaderRefresh ref="vLoaderRefresh" @load="loadData" :minHeight="lRefreshMinHeight">
  <div class="l-main">
    <div class="l-left-line" v-show="listBigCurrCount"></div>
    <div class="l-left-line l-left-line2" v-show="listBigCurrCount"></div>
    <div class="l-list" v-click="onListClick">
      <div class="l-date-item" v-for="(list,date) in listDict" :key="date">
        <div class="l-date">
          <i class="iconfont l-t-ioc">&#xe6c7;</i>
          {{date}}
        </div>
        <div>
          <div class="l-item" v-for="(item,i) of list" :key="item.id" :data-index="i" :data__itemData.prop="item">
            <div v-if="status==='0'" class="l-r-oper" key="oper">
              <BaseButton v-if="isLeader" class="l-btn" s="green">通过</BaseButton>
              <BaseButton class="l-btn" s="blue">编辑</BaseButton>
              <BaseButton v-if="isLeader" class="l-btn" s="red">拒绝</BaseButton>
            </div>
            <div v-else-if="status==='1'" class="l-r-oper" key="oper">
              <!-- <BaseButton class="l-btn" s="red">拒绝</BaseButton> -->
              <!-- <BaseButton class="l-btn" s="gray">撤销</BaseButton> -->
              <BaseButton v-if="isLeader" class="l-btn" s="green">通过</BaseButton>
              <BaseButton class="l-btn" s="blue">编辑</BaseButton>
            </div>
            <div v-else-if="status==='2'" class="l-r-oper" key="oper">
              <BaseButton v-if="isLeader" class="l-btn" s="gray">撤销</BaseButton>
            </div>
            <div class="l-date-d">
              {{formatDate(date+','+item.start_time, 'yyyy年MM月dd日 hh时mm分')}}
            </div>
            <div class="l-des">
              <i class="l-c-ioc"></i>
              <span class="l-t">{{item.subject_name[0]}}</span>
              <span class="l-name">{{item.user_name}}</span>
              <span class="l-class">{{item.class_room_name}}</span>
            </div>
            <div class="l-gist">{{item.name}}</div>
          </div>
        </div>
      </div>
    </div>
  </div>
  <div ref="noData" class="no-data l-no-data" v-show="noData"></div>
  </LoaderRefresh>

  <!-- <LoaderBottom ref="vLoaderBottom" @loadData="loadData"/> -->
  <!-- <div class="l-msg-none" v-show="isFinish&&listBigCurrCount===0">{{msgNone}}</div> -->
</div>
</template>
<script>
import VHeader from '@/components/VHeader'
import BaseButton from '@/components/BaseButtonBorder'
import formatDate from '@/modules/corejs/time/format-date/format-date.js'
import scopeElements from '@/modules/corejs/dom/scope-elements.js'
// import LoaderBottom from '@/modules/loader-bottom/LoaderBottom'
import LoaderRefresh from '@/modules/loader-refresh'
import getIsLeader from '@/js/get-is-leader.js'
export default {
  data () {
    return {
      status: '0', // 0待审核 1未通过 2已通过
      listDict: {},
      isFinish: false,
      page: 0,
      isLeader: false,
      noData: false,

      lRefreshMinHeight: 0
    }
  },
  created () {
    getIsLeader().then(isLeader => {
      this.isLeader = isLeader
    })
  },
  mounted () {
    this.setMinHeight()
  },
  computed: {
    // listBigCurrCount () {
    //   let listBig = this.listDict[this.status]
    //   let num = 0
    //   listBig && this.each(listBig, function () { num++ })
    //   return num
    // },
    listBigCurrCount () {
      let num = 0
      this.each(this.listDict, function () { num++ })
      return num
    }
    // msgNone () {
    //   return ({
    //     0: '没有待审批数据',
    //     1: '没有未通过数据',
    //     2: '没有已通过数据'
    //   })[this.status]
    // }
  },
  beforeRouteEnter (to, from, next) {
    // chrome bug。开启控制台后不触发 afterEach
    next(vm => {
      vm.$loading.hide()
    })
  },
  methods: {
    formatDate,
    each (obj, fn) {
      for (let k in obj) {
        if (obj.hasOwnProperty(k) && fn(obj[k], k) === false) break
      }
    },
    loadData ({isRefresh, complete, vLoaderBottom}) {
      if (isRefresh) { // 刷新情况 清空
        this.page = 0
      } else {
        vLoaderBottom.show()
      }
      let listNum = 10 // 每页条数
      this.$axios.get('/lecture/v2/listenlist', { params: {
        is_history: 0,
        list_mun: listNum,
        // page: this.page++,
        offset: (this.page++ * listNum),
        status: this.status
      } }).then(({data}) => {
        if (data.status === 200) {
          if (isRefresh) { // 刷新情况 清空
            this.listDict = {}
          }

          let {listenList} = data.result
          this.mergeListData(listenList)
          return listenList.length === 0
        }
        this.$toast.error(data.message)
        return true
      }).catch(e => { this.$toast.error(e.message); return true }).then((isFinish) => {
        this.isFinish = isFinish
        complete(isFinish)

        // 完全没有数据情况效果
        this.noData = true
        this.each(this.listDict, () => {
          this.noData = false
          return false
        })
        if (this.noData) {
          vLoaderBottom.hide()
        }
      })
    },
    switchState (state) {
      if (this.status === state) return
      this.noData = false
      this.status = state
      this.page = 0
      this.listDict = {}
      this.$nextTick(function () {
        let {vLoaderRefresh} = this.$refs
        vLoaderRefresh.reStart()
      })
    },
    getDate (date) {
      return date.split('T')[0]
    },
    mergeListData (list) {
      // keyHandle：定制 key 情况
      function dictCreate (list, name, keyHandle = k => k) {
        let newList = {}
        list.forEach(item => {
          let key = keyHandle(item[name])
          let child = newList[key]
          if (child === undefined) {
            child = newList[key] = []
          }
          child.push(item)
        })
        return newList
      }

      let newList = dictCreate(list, 'lesson_date', function (k) {
        return k.split('T')[0]
      })

      let {listDict} = this
      this.each(newList, (list, kDate) => {
        let currList = listDict[kDate] || []
        this.$set(listDict, kDate, currList.concat(list))
      })
    },

    // "status": 2, // 1表示拒绝或撤销, 2表示通过
    // "course_id": 3933568871211445515 // 公开课ID
    audit (data) {
      this.$loading.show()
      return this.$axios.post('/lecture/v1/approveOpenCourse', data).then(({data}) => {
        if (data.status === 200) {
          let {result} = data
          if (result.success) {
            this.$toast.success('审批成功')
            return true
          } else {
            let msg = ' 审批失败'
            switch (result.type) {
              case 0:
                msg = '没有审批权限'
                break
              case 1:
                msg = '提交的课程ID不存在'
                break
              case 2:
                msg = '审批有效时间已过'
                break
              case 3:
                msg = '后台异常'
                break
            }
            this.$toast.error(msg)
          }
        } else {
          this.$toast.error(data.message)
        }
      }).catch(e => { this.$toast.error(e.message) }).then((isSucceed) => {
        this.$loading.hide()
        return isSucceed
      })
    },
    auditSucceedHandle (itemData, index) {
      let {listDict} = this
      let kDate = this.getDate(itemData.lesson_date)
      let list = listDict[kDate]
      list.splice(index, 1)

      if (list.length === 0) {
        this.$delete(listDict, kDate)
      }
    },
    onListClick ({target}, {elm}) {
      scopeElements(target, elem => {
        if (elem === elm) return false
        let {className} = elem
        if (/red/.test(className)) { // 拒绝
          let parentElement = elem.parentElement.parentElement
          let itemData = parentElement.data__itemData
          let id = itemData.id
          this.audit({
            status: '1',
            course_id: id
          }).then(isSucceed => {
            if (isSucceed) {
              // this.dataMove(itemData, '1', parentElement.dataset.index)
              this.auditSucceedHandle(itemData, parentElement.dataset.index)
            }
          })
          return false
        }
        if (/gray/.test(className)) { // 撤销
          let parentElement = elem.parentElement.parentElement
          let itemData = parentElement.data__itemData
          let id = itemData.id
          this.audit({
            status: '1',
            course_id: id
          }).then(isSucceed => {
            if (isSucceed) {
              // this.dataMove(itemData, '0', parentElement.dataset.index)
              this.auditSucceedHandle(itemData, parentElement.dataset.index)
            }
          })
          return false
        }
        if (/green/.test(className)) { // 同意
          let parentElement = elem.parentElement.parentElement
          let itemData = parentElement.data__itemData
          let id = itemData.id
          this.audit({
            status: '2',
            course_id: id
          }).then(isSucceed => {
            if (isSucceed) {
              // this.dataMove(itemData, '2', parentElement.dataset.index)
              this.auditSucceedHandle(itemData, parentElement.dataset.index)
            }
          })
          return false
        }
        if (/blue/.test(className)) { // 编辑
          let itemData = elem.parentElement.parentElement.data__itemData
          this.$router.push({
            name: 'EditLectures',
            params: itemData
          })
          return false
        }
      })
    },
    setMinHeight () {
      // 下拉刷新内容太少，高度不够解决方案
      let winHeight = window.innerHeight
      this.lRefreshMinHeight = winHeight - 60
      this.$refs.noData.style.height = winHeight - 200 + 'px'
    }
  },
  components: {
    VHeader,
    BaseButton,
    LoaderRefresh
  }
}
</script>

<style scoped>

.l-tab-box {
  height: 38px;
  text-align: center;
  position: fixed;
  top:0;
  width: 100%;
  z-index: 1;
}
.l-tab{
  display: inline-block;
  margin-top: 6px;
  color: #13b7f6;

  .l-tab-btn{
    float: left;
    border:1PX solid #13b7f6;
    border-left-width:0;
    padding: 4px 10px;
    background-color: #fff;
    &.selected {
      background-color: #13b7f6;
      color: #fff;
    }
    &:first-child{
      border-left-width:1PX;
      border-radius:100px 0 0 100px;
    }
    &:last-child{
      border-radius:0 100px 100px 0;
    }
  }
}

.l-main {
  margin-left: 50px;
  margin-top: 60px;
  margin-right: 15px;
  padding-bottom: 20px;
  position: relative;
  .l-left-line {
    position: fixed;
    left: 24px;
    width: 2px;
    height: 8000px;
    background-color: #108ee9;
  }
  .l-left-line2{
    position: absolute;
    left: -26px;
    height: 100%;
  }
}

.l-date-item {
  padding-top: 20px;
  &:first-child {
    padding-top: 0;
  }
  .l-date {
    font-size: 18px;
    color: #108ee9;
    padding-bottom: 7px;
  }
  .l-t-ioc {
    position: absolute;
    /* left: 14px; */
    left: -36px;
    width: 23px;
    height: 23px;
    font-size: 22px;
    line-height: 1.1;
    background-color: #f3f3f4;
    color: #108ee9;
  }
}
.l-item {
  border-top: 1px solid #ddd;
  padding-top: 10px;
  margin-top: 15px;
  &:first-child {
    border-top:0;
    padding-top: 0;
    margin-top: 0;
  }
  .l-date-d {
    font-size: 15px;
    color: #999;
    margin: 4px 0;
  }

  .l-des {
    padding: 5px 0;
  }
  .l-c-ioc {
    position: absolute;
    /* left: 18px; */
    left: -32px;
    margin-top: 6px;
    border: 2px solid #108ee9;
    width: 10px;
    height: 10px;
    border-radius: 50%;
    background-color: #f3f3f4;
  }
  .l-t {
    font-size: 18px;
    color: #13b7f6;
    border: 2px solid #13b7f6;
    display: inline-block;
    font-weight: bold;
    padding: 2px;
    border-radius: 4px;
  }
  .l-name {
    font-size: 18px;
    color: #666;
    font-weight: bold;
  }
  .l-class {
    font-size: 15px;
    color: #999;
  }

  .l-gist {
    font-size: 15px;
    color: #666;
    padding: 6px 0;
  }

  .l-r-oper {
    position: absolute;
    right: 0;
    width: 104px;
    .l-btn{
      margin-bottom: 7px;
      /* margin-right: 15px; */
      float: right;
    }
  }
}
.l-msg-none {
  text-align: center;
}
.l-no-data {
  background-size: 50% auto;
  pointer-events: none;
}
</style>
